<template>
  <view class="wrapper">
		<tabBar :currentIndex="1"></tabBar>
    <view class="header">
      <u-input v-model="listQuery.title"
               placeholder="请输入标题"
               maxlength="30"
               type="textarea"
               class="input" />
      <text class="input-number">{{listQuery.title.length}}/30</text>
    </view>
    <view class="content">
      <div class="editor">
        <div ref="toolbar"
             class="toolbar"></div>
        <div ref="editor"
             :contenteditable="true"
             class="editor-content"></div>
      </div>
    </view>
    <view class="name">帖子所属专业（可选择三个专业或默认全部专业）</view>
    <view class="name-list flex-center">
      <view v-for="(item,index) in subjectCheckList"
            class="name-item">{{ item.title }}</view>
    </view>
    <view class="all-btn"
          @click="chooseProject">选择专业</view>
    <view class="footer-list">
      <view class="list-item flex-between">
        <view class="list-item-left">
          <view class="title">是否付费阅读</view>
          <view class="desc">默认展示帖子前50个文字，其余内容付费阅读</view>
        </view>
        <view>
          <u-switch v-model="listQuery.checked"></u-switch>
          <view class="money-wrapper" v-if="listQuery.checked">
            <view class="cont">¥ </view>
            <u-input class="money-style"
                     v-show="listQuery.checked"
                     color="#21D2FF"
                     style="width: 60px;color:#21D2FF"
                     type="digit"
                     maxlength="6"
                     v-model="listQuery.money"
										 @blur="onlyNumAndPoint(2)"
                     placeholder="请输入" />
          </view>
        </view>
      </view>
      <view class="list-item flex-between">
        <view class="title">允许阅读的人</view>
        <view class="radio-item">
          <u-radio-group v-model="listQuery.viewRange">
            <u-radio v-for="(item, index) in list"
                     :key="index"
                     :name="item.value">
              {{item.name}}
            </u-radio>
          </u-radio-group>
        </view>
      </view>
      <view class="list-item">
        <view class="title">上传附件</view>
        <view class="flex-between annex-list"
              v-for="(item, index) in attachList">
          <view class="attachName">{{ item.attachName }}</view>
          <image src="/static/img/close.png"
                 class="close-icon"
                 @click="delAttachList(index)"></image>
        </view>
        <view class="all-btn"
              @click="chooseFile">添加附件</view>

      </view>
    </view>
    <view class="add-btn"
          @click="submit">{{ id ?'修改' : '提交' }}</view>
    <u-modal v-model="show"
             title="请选择专业"
             :show-cancel-button="true"
             @confirm="confirmReject">
      <view class="table-list flex-between">
        <view :class="['list-item', item.isChecked && 'active' ]"
              v-for="(item, index) in dictList"
              :key="index"
              @click="choose(index)">{{ item.title }}</view>
      </view>
    </u-modal>
  </view>
</template>

<script>
	import tabBar from '@/components/tabBar.vue'
import apis from "@/apis.js";
import store from "@/store/index.js";
import E from "wangeditor";
import { mapState, mapActions, mapMutations } from "vuex";
export default {
	components: {
		tabBar
	},
  computed: {
    ...mapState(["TOKEN", "img_url", "userInfo"]),
  },
  data() {
    return {
      editorData: null,
      apis: apis,
      show: false,
      content: "",
      list: [
        {
          name: "全部",
          value: 0,
        },
        {
          name: "关注我的人",
          value: 1,
        },
      ],
      dictList: [],
      edits: [],
      editor: null,
      listQuery: {
        id: null,
        title: "",
        content: "",
        viewRange: 0,
        checked: false,
        subjectType: "",
      },
      subjectCheckList: [],
      attachList: [],
      id: null,
    };
  },
  onLoad(options) {
		this.getDiceData();
		this.subjectCheckList = [];
		this.attachList = [];
		if (this.editor) {
		  this.editor.txt.html("");
		}
		this.listQuery = {
		  id: null,
		  title: "",
		  content: null,
		  viewRange: 0,
		  checked: false,
		  subjectType: "",
		};
		this.id = options.id
		this.listQuery.id = options.id;
	},
	onShow() {
		
		if (this.id) {
		  this.getDeail();
		}
	},
  // onHide() {
  //   uni.setStorageSync("invitationID", "");
  // },
  mounted() {
    this.editor = new E(this.$refs.toolbar, this.$refs.editor);
    this.editor.config.menus = [
      "bold", // 粗体
      "foreColor", // 文字颜色
      "image", // 插入图片
      "video", // 插入视频
    ];

    console.log("this.editor", this.editor);
    this.editor.config.uploadImgServer = apis.uploadImage; // 上传接口
    this.editor.config.height = 400; // 上传接口
    this.editor.config.uploadImgHeaders = {
      Authorization: store.state.TOKEN,
    }; // 上传接口
    this.editor.config.uploadFileName = "file"; // 上传文件参数名
    this.editor.config.uploadImgHooks = {
      // 上传完成处理方法
      customInsert: function (insertImg, result) {
        if (result.code === 0) {
          insertImg(`${store.state.img_url}${result.message}`);
        } else {
          uni.showToast({
            title: result.message,
            icon: "none",
          });
        }
      },
    };

    this.editor.config.uploadVideoServer = apis.uploadImage; // 上传接口
    this.editor.config.uploadVideoHeaders = {
      Authorization: store.state.TOKEN,
    }; // 上传接口
    this.editor.config.uploadVideoName = "file"; // 上传文件参数名
    this.editor.config.uploadVideoHooks = {
      // 上传完成处理方法
      customInsert: function (insertImg, result) {
        if (result.code === 0) {
          insertImg(`${store.state.img_url}${result.message}`);
        } else {
          uni.showToast({
            title: result.message,
            icon: "none",
          });
        }
      },
    };
    let _this = this;
    this.editor.config.onchange = function (newHtml) {
      console.log(
        "🚀 ~ file: setPost.vue ~ line 191 ~ mounted ~ newHtml",
        newHtml
      );
      // 监控变化，同步更新到 textarea
      _this.listQuery.content = newHtml;
    };
    this.editor.create();
    // this.test()
  },
  methods: {
		//文本框限制输入数字和点
		onlyNumAndPoint(num) {
		    //先把非数字的都替换掉，除了数字和.
		    this.listQuery.money = this.listQuery.money.replace(/[^\d.]/g, "");
		    //必须保证第一个为数字而不是.
		    this.listQuery.money = this.listQuery.money.replace(/^\./g, "");
		    //保证只有出现一个.而没有多个.
		    this.listQuery.money = this.listQuery.money.replace(/\.{2,}/g, ".");
		    //保证.只出现一次，而不能出现两次以上
		    this.listQuery.money = this.listQuery.money.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
		
		    // 最多保留num位小数
		    if(num){
		     var re = /.\.\d{3,}/g;
		     if(re.test(this.listQuery.money)){
		         this.listQuery.money = parseFloat(Number(this.listQuery.money).toFixed(num)); //parseFloat()使其结果如果为整数的话,就会显示整数而不会显示.00的情况.
		     }
		    }
		},
    /**
     *  @function 获取详情
     */
    getDeail() {
      this.$http.get(`${apis.article_detail}/${this.id}`).then((res) => {
        if (res.data.code === 200) {
          this.listQuery.title = res.data.result.title;
          this.listQuery.content = res.data.result.content;
          this.listQuery.money = res.data.result.money;
          this.listQuery.payFlag = res.data.result.payFlag;
          this.listQuery.checked =
            res.data.result.payFlag === "1" ? true : false;
          this.listQuery.subjectType = res.data.result.subjectType;
          this.listQuery.attachList = res.data.result.qtcAttachList;
          this.attachList = res.data.result.qtcAttachList;
          this.listQuery.viewRange = res.data.result.viewRange;
          let subjectValues = this.listQuery.subjectType.split(",");
          console.log(this.listQuery.content, "12323132");
          this.$nextTick(() => {
            this.editor.txt.html(this.listQuery.content || "");
          });
          this.dictList.forEach((item) => {
            subjectValues.forEach((keys, ind) => {
              if (item.value === keys) {
                item.isChecked = true;
              }
            });
          });
          this.confirmReject();
        }
      });
    },
    /**
     *  @function 获取专业
     */
    getDiceData() {
      this.$http.get(`${apis.getDictItems}/subject_type`).then((res) => {
        if (res.data.code === 0) {
          this.dictList = res.data.result;
          this.dictList.forEach((item) => {
            item.isChecked = false;
          });
        }
      });
    },
    /**
     *  @function 保存富文本
     */
    onSave(data) {
      this.listQuery.content = data.html;
    },
    /**
     *  @function 选择专业
     */
    choose(index) {
      this.dictList[index].isChecked = !this.dictList[index].isChecked;
      this.$forceUpdate();
    },
    /**
     * @function 删除专业
     * @param {Object} index
     */
    delAttachList(index) {
      this.attachList.splice(index, 1);
    },
    chooseProject() {
      this.show = true;
    },
    getValue(data) {
      console.log(data);
    },
    submit() {
      let userInfo = this.$store.state.userInfo;
      let flag = false;
      if (userInfo.authenticationFlag === "2" || userInfo.starFlag === "1") {
        flag = true;
      } else {
        uni.showModal({
          title: "提示",
          content: "认证后才能进行该操作，是否前往认证？",
          success(res) {
            if (res.confirm) {
              uni.navigateTo({
                url: "/pages/authentication/remind?auditType=1",
              });
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      }
      if (!flag) {
        return;
      }
      if (this.listQuery.checked && !Number(this.listQuery.money)) {
        uni.showToast({
          title: "请填写金额",
          icon: "none",
        });
        return;
      }
      if (!this.listQuery.title) {
        uni.showToast({
          title: "请输入标题",
          icon: "none",
        });
        return;
      }
      if (!this.editor.txt.html()) {
        uni.showToast({
          title: "请输入帖子内容",
          icon: "none",
        });
        return;
      }
			if (!this.listQuery.title || !this.subjectCheckList.length) {
        uni.showToast({
          title: "请选择帖子所属专业",
          icon: "none",
        });
        return;
      }
      
			let checkedList = this.dictList.filter(item => item.isChecked)
			if (this.subjectCheckList.length > 3) {
				 uni.showToast({
          title: "专业最多只能选3个",
          icon: "none",
        });
        return;
			}

      this.listQuery.attachList = this.attachList;
      this.listQuery.subjectType = this.subjectCheckList
        .map((item) => item.value)
        .join(",");
      this.listQuery.payFlag = this.listQuery.checked === true ? "1" : "0";
      this.listQuery.content = this.editor.txt.html();
      this.$http.post(apis.articleSend, this.listQuery).then((res) => {
        if (res.data.code === 200) {
          if (!this.id) {
            uni.showToast({
              title: "帖子审核通过后方能显示，请等待！",
              icon: "none",
            });
          } else {
            uni.showToast({
              title: "操作成功",
              icon: "none",
            });
          }
					
          
					this.subjectCheckList = [];
					this.attachList = [];
					this.editor.txt.html("");
					this.dictList.forEach((item) => {
					  item.isChecked = false;
					});
					this.listQuery = {
					  id: null,
					  title: "",
					  content: null,
					  viewRange: 0,
					  checked: false,
					  subjectType: "",
					};
          if (!this.id) {
            setTimeout(() => {
              uni.navigateBack({})
            }, 1000);
          }
          
        }
      });
    },
    /**
     *  @function 确认选择专业
     */
    confirmReject() {
      this.subjectCheckList = this.dictList.filter((item) => {
        if (item.isChecked) {
          return item;
        }
      });
    },
    chooseFile() {
      let that = this;
      uni.chooseImage({
        count: 1, //默认100
        success: (res) => {
          let tempFilePaths = res.tempFilePaths;
          let tempFiles = res.tempFiles;
          console.log(res);
          uni.uploadFile({
            url: apis.uploadImage, //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            name: "file",
            header: {
              Authorization: that.TOKEN,
            },
            success: (uploadFileRes) => {
              let data = JSON.parse(uploadFileRes.data);
              let param = {
                attachName: tempFiles[0].name,
                attachUrl: data.message,
              };
              that.attachList.push(param);
            },
          });
        },
      });
    },
  },
};
</script>

<style lang="scss">
	.wrapper {
		padding-bottom: 100rpx;
	}
.money-wrapper {
  display: flex;
  align-items: center;
  border: 2rpx solid #21d2ff;
  color: #21d2ff !important;
  padding: 2rpx;
	padding-left: 10rpx;
  justify-content: center;
  opacity: 1;
  border-radius: 8rpx;
  .cont {
    margin-right: 10rpx;
  }
}
.money-style {
  // width: 128rpx;
  // height: 42rpx;
  color: #21d2ff !important;
  text-align: center;
  .u-input__input {
    color: #21d2ff !important;
  }
}
</style>
<style lang="scss" scoped>
.wrapper {
  padding: 30rpx;
  .add-btn {
    width: 160px;
    height: 32px;
    background: #3fa7ff;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16);
    opacity: 1;
    border-radius: 2px;
    color: #ffffff;
    font-size: 16px;
    margin: 0 auto;
    text-align: center;
    line-height: 32px;
    margin-bottom: 60px;
  }
  .name-list {
    margin-top: 20px;
    padding: 0 20px;
    width: 100%;
    flex-wrap: wrap;
    .name-item {
      height: 33px;
      border: 1px solid #21d2ff;
      opacity: 1;
      border-radius: 4px;
      text-align: center;
      line-height: 33px;
      color: #21d2ff;
      font-size: 16px;
      margin: 10px;
      padding: 0 10px;
    }
  }
  .table-list {
    padding: 30rpx;
    flex-wrap: wrap;
    .list-item {
      width: 114px;
      height: 33px;
      border: 1px solid #bfbfbf;
      opacity: 1;
      border-radius: 4px;
      line-height: 33px;
      text-align: center;
      color: #4d5b80;
      font-size: 16px;
      margin: 10px 10px;
    }
    .active {
      border: 1px solid #21d2ff;
      color: #21d2ff;
    }
  }
  .footer-list {
    .list-item {
      color: #4d5b80;
      font-size: 16px;
      width: 100%;
      border-top: 1px solid #bfbfbf;
      padding: 20px 0;
      .annex-list {
        width: 250px;
        height: 37px;
        background: #21d2ff;
        opacity: 1;
        border-radius: 4px;
        color: #ffffff;
        text-align: center;
        padding: 0 20px;
        margin: 10rpx auto;
        overflow: hidden;
      }
      .attachName {
        word-break: break-all;
      }
      .close-icon {
        width: 16.5px;
        height: 16.5px;
      }
      .add-other {
        width: 250px;
        height: 37px;
        border: 1px solid #21d2ff;
        opacity: 1;
        border-radius: 4px;
        text-align: center;
        color: #21d2ff;
        line-height: 37px;
        margin: 20px auto;
      }
      .list-item-left {
        .title {
          color: #4d5b80;
          font-size: 16px;
        }
        .desc {
          color: #949494;
          font-size: 12px;
          margin-top: 20px;
        }
      }
    }
  }
  .editor-content {
    box-sizing: border-box;
    border: 2rpx solid #ddd;
    height: 300px;
  }
  .content {
    width: 100%;
    // height: 400px;
    // background: #E9EBF4;
    opacity: 1;
    position: relative;
    z-index: 1;
    border-radius: 4px;
    margin-top: 20px;

    .editor {
      // height: 400px;
      // overflow-y: auto;
    }
    .editor-content {
      // height: 600px;
      // overflow-y: auto;
    }
    .textarea {
      text-indent: 20px;
      padding: 20px;
    }
  }
  .name {
    color: #4d5b80;
    font-size: 16px;
    margin-top: 24px;
  }
  .all-btn {
    width: 250px;
    height: 37px;
    background: #21d2ff;
    opacity: 1;
    border-radius: 4px;
    text-align: center;
    line-height: 37px;
    font-size: 16px;
    color: #ffffff;
    margin: 30px auto;
  }
  .header {
    position: relative;
    .input {
      width: 100%;
      height: 50px;
      background: #e9ebf4;
      opacity: 1;
      border-radius: 4px;
      color: #4d5b80;
      font-size: 16px;
      line-height: 40px;
      text-indent: 20px;
    }
    .input-number {
      position: absolute;
      right: 0;
      font-size: 14px;
      bottom: 10px;
      right: 10px;
    }
  }
}
div * {
  -webkit-user-select: text;
  outline: none;
}
.w-e-text-container{
    height: 400px !important;/*!important是重点，因为原div是行内样式设置的高度300px*/
}
</style>
